//
//  QRCodeScanViewController.m
//  DBAChain
//
//  Created by Mxionlly on 2018/9/11.
//  Copyright © 2018年 Evan. All rights reserved.
//

#import "QRCodeScanViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "ZXingObjC.h"
#define _ZXINGOBJC_

@interface QRCodeScanViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIWebViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIView * actionView;
    UIView *navView;
    UIImageView     * _scanView;
    UIImageView     * _lineView;
}

@property (nonatomic ,strong) AVCaptureSession * captureSession;                 //捕捉会话
@property (nonatomic, strong) AVCaptureVideoPreviewLayer * videoPreviewLayer;    //预览图层layer
@property (strong, nonatomic) UIView * boxView;//扫描识别框

@property (nonatomic, strong) UIImagePickerController * imagePickerController;

@end

@implementation QRCodeScanViewController

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_captureSession startRunning];
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"扫描二维码";
    [self layoutUI];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(judgeCameraAuth) userInfo:nil repeats:NO];
    [self startScan];
}

//判断相机权限
- (void)judgeCameraAuth
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        [[UIAlertController alloc]alertTitle:@"请允许访问您的相机" alertMessage:@"相机服务请开启,请进入系统设置【设置】>【隐私】>【相机】中打开开关,并允许使用相机"  leftCancelTitle:@"确定" leftCancel:^(UIAlertAction *action) {
            
        } rightTitle:nil rightOK:nil];
    }
}

- (void)layoutUI
{
    navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 64)];
    navView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:navView];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    backBtn.frame = CGRectMake(0, 20, 80, 44);
    backBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [backBtn setTitle:@"取消" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(clickBackBtn) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
}

//返回
- (void)clickBackBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

//调用相册
- (void)clickalbumBtn
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        [[UIAlertController alloc]alertTitle:@"请允许访问您的相册" alertMessage:@"相册服务请开启,请进入系统设置【设置】>【隐私】>【相册】中打开开关,并允许使用相册"  leftCancelTitle:@"确定" leftCancel:^(UIAlertAction *action) {
            
        } rightTitle:nil rightOK:nil];

    }else{
        [_captureSession stopRunning];
        
        if (!_imagePickerController) {
            
            _imagePickerController = [[UIImagePickerController alloc] init];
            _imagePickerController.delegate = self;
            _imagePickerController.allowsEditing = YES;
            _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
    }
}

//开始扫描
- (void)startScan
{
    //初始化设备(摄像头)
    NSError *error = nil;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (error)
    {
        NSLog(@"没有摄像头:%@", error.localizedDescription);
        return;
    }
    
    //创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    //实例化捕捉会话并添加输入,输出流
    if (!_captureSession) {
        _captureSession = [[AVCaptureSession alloc] init];
    }
    
    //高质量采集率
    [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
    
    [_captureSession addInput:input];
    [_captureSession addOutput:output];
    
    //设置输出的代理,在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];   //用串行队列新线程结果在UI上显示较慢
    
    //扫码类型
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,         //二维码
                                     AVMetadataObjectTypeCode39Code,     //条形码   韵达和申通
                                     AVMetadataObjectTypeCode128Code,    //CODE128条码  顺丰用的
                                     AVMetadataObjectTypeCode39Mod43Code,
                                     AVMetadataObjectTypeEAN13Code,
                                     AVMetadataObjectTypeEAN8Code,
                                     AVMetadataObjectTypeCode93Code,    //条形码,星号来表示起始符及终止符,如邮政EMS单上的条码
                                     AVMetadataObjectTypeUPCECode]];
    
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //添加预览图层
    _videoPreviewLayer.frame = self.view.bounds;
    [self.view.layer addSublayer:_videoPreviewLayer];
    [self.view bringSubviewToFront:self.view.subviews[0]];
    
    
    //扫描范围
    UIImage *scanImage = [UIImage imageNamed:@"main_scanscanBg_icon"];
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    CGFloat scanW = 236;
    CGRect scanFrame = CGRectMake(width / 2. - scanW / 2. , height / 2. - scanW / 2., scanW, scanW);
    
    //扫描范围方框
    _scanView = [[UIImageView alloc] initWithImage:scanImage];
    _scanView.backgroundColor = [UIColor clearColor];
    _scanView.frame = scanFrame;
    [self.view addSubview:_scanView];
    
    //扫描识别范围
    output.rectOfInterest = CGRectMake(0 / self.view.bounds.size.height,
                                       0  / self.view.bounds.size.width,
                                       KScreenWidth/ self.view.bounds.size.width,
                                       KScreenHeight / self.view.bounds.size.height);
    
    //开始扫描
    [_captureSession startRunning];
    [self loopDrawLine];
    [self setOverView];
    
}

#pragma mark 照片处理
-(void)getInfoWithImage:(UIImage *)img{
    
    UIImage *loadImage= img;
    CGImageRef imageToDecode = loadImage.CGImage;
    
    ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
    ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
    
    NSError *error = nil;
    
    ZXDecodeHints *hints = [ZXDecodeHints hints];
    
    ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
    ZXResult *result = [reader decode:bitmap
                                hints:hints
                                error:&error];
    
    if(result)
    {
        NSLog(@"相册图片QRCodeString == %@",result.text);
        [self handleResultOfScaningQRCodeString:result.text];
    }else{
        [self handleResultOfScaningQRCodeString:result.text];
        [DKProgressHUD showErrorWithStatus:@"二维码识别失败"];
        //[_captureSession startRunning];
    }
}

#pragma mark - 扫描结果代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        [self handleResultOfScaningQRCodeString:obj.stringValue];
    }
}

//从相机扫描或者从相册选取二维码后的跳转判断
- (void)handleResultOfScaningQRCodeString:(NSString *)QRCodeString
{
    if ([QRCodeString containsString:@"ids="]) {
        [_captureSession stopRunning];
        [self.navigationController popViewControllerAnimated:YES];
        self.blockQR(QRCodeString);
        //写
        return;
        
    } else{
        [_captureSession stopRunning];
        self.blockQR(QRCodeString);
        [self.navigationController popViewControllerAnimated:YES];
        //写
        return;
    }
}

#pragma - mark - UIImagePickerViewControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [self getInfoWithImage:image];
    [self dismissViewControllerAnimated:NO completion:^{
        
        
    }];
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_captureSession startRunning];
    
    [self.imagePickerController dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - 动画
- (void)loopDrawLine {
    
    UIImage *lineImage = [UIImage imageNamed:@"main_scanLine_icon"];
    
    CGFloat w = CGRectGetWidth(_scanView.frame);
    CGFloat h = CGRectGetHeight(_scanView.frame);
    
    CGRect start = CGRectMake(0, 0, w, 2);
    CGRect end = CGRectMake(0, h - 2, w, 2);
    
    if (!_lineView) {
        _lineView = [[UIImageView alloc] initWithImage:lineImage];
        _lineView.frame = start;
        [_scanView addSubview:_lineView];
    } else {
        _lineView.frame = start;
    }
    
    __weak typeof(self) weakSelf = self;
    
    [UIView animateWithDuration:2 animations:^{
        _lineView.frame = end;
        
    } completion:^(BOOL finished) {
        [weakSelf loopDrawLine];
        
    }];
}

#pragma mark - 添加模糊效果
- (void)setOverView {
    
    CGFloat nwidth = CGRectGetWidth(self.view.frame);
    
    CGFloat x = CGRectGetMinX(_scanView.frame);
    CGFloat y = CGRectGetMinY(_scanView.frame);
    CGFloat w = CGRectGetWidth(_scanView.frame);
    CGFloat h = CGRectGetHeight(_scanView.frame);
    
    [self creatView:CGRectMake(0, 0, nwidth, y)];
    [self creatView:CGRectMake(0, y, x, h)];
    [self creatView:CGRectMake(0, y + h, nwidth, CGRectGetHeight(self.view.frame) - y - h)];
    [self creatView:CGRectMake(x + w, y, nwidth - x - w, h)];
    
    UILabel *tittleLb = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMidX(_scanView.frame) - 23, KScreenWidth, 17)];
    tittleLb.text = @"将二维码放入框中，即可自动扫描";
    tittleLb.textColor = [UIColor whiteColor];
    tittleLb.font = [UIFont systemFontOfSize:16];
    tittleLb.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:tittleLb];
}

- (void)creatView:(CGRect)rect {
    CGFloat alpha = 0.5;
    UIColor *backColor = [UIColor blackColor];
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.backgroundColor = backColor;
    view.alpha = alpha;
    [self.view insertSubview:view belowSubview:navView];
}

#pragma mark 获取扫描区域
-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width, height);
}

@end
